
import Request from 'luch-request';

import useUserStore from "@/store/user.ts"
const userStore = useUserStore()


const http = new Request({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 8000,
  method: 'GET',
  header: {
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=UTF-8',
    platform: "WechatMiniProgram",
  },
  custom: {
    // 显示请求时loading模态框 默认显示
    showLoading: true,
    // loading提醒文字
    loadingMsg: '加载中',
    // 需要授权才能请求
    auth: true,
  },
});


http.interceptors.request.use(
  (config) => {
    const token = uni.getStorageSync('token');
    if (config.custom.auth && !userStore.isLogin) {
        userStore.setAuth('wechatMiniLogin')
      return Promise.reject();
    }
    if (config.custom.showLoading) {
        uni.showLoading({
          title: config.custom.loadingMsg,
          mask: true,
          fail: () => {
            uni.hideLoading()
          },
        });
    }
    if (token) config.header['Authorization'] = token;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

/**
 * @description 响应拦截器
 */
http.interceptors.response.use(
  (response) => {
    // 自动设置登陆令牌
    if (response.config.url.includes('no-auth/wechat/getWechatUserAuth')) {
        userStore.setToken(response.data?.token)
    } else if (response.config.url.includes('no-auth/wechat/getSessionId')) {
      userStore.setToken(response.data?.data?.token)
    }
    response.config.custom.showLoading && uni.hideLoading()
    const { data } = response
    if (data && data.code && data.code !== 200){
      let errorMsg = data.msg
      if (data.code === 401){
        if (userStore.isLogin) {
          errorMsg = '您的登录已过期'
        } else {
          errorMsg = '请先登录'
        }
        userStore.logout()
      }
      else {
        uni.showToast({
          title: errorMsg,
          icon: 'none',
          mask: true,
        });
      }
      return Promise.reject(errorMsg)
    }
    return Promise.resolve(data);
  },
  (error) => {
    return error;
  },
);


const request = (config) => {
  return http.middleware(config);
};
export default request;
